import { ref, onMounted, onUnmounted } from 'vue';

export function useLoopPlayback(sourceVideo, startTime, endTime) {
  const isLooping = ref(false);
  
  // 循环播放控制
  const toggleLoopPlay = () => {
    console.log('切换循环播放状态');
    isLooping.value = !isLooping.value;
    
    if (!sourceVideo.value) {
      console.error('视频元素不存在');
      return;
    }
    
    if (isLooping.value) {
      console.log(`开始循环播放: ${startTime.value}s - ${endTime.value}s`);
      // 设置视频到开始时间并播放
      sourceVideo.value.currentTime = startTime.value || 0;
      sourceVideo.value.play().catch(err => {
        console.error('播放失败:', err);
        isLooping.value = false;
      });
    } else {
      console.log('停止循环播放');
      sourceVideo.value.pause();
    }
  };

  // 监听视频时间更新
  const handleTimeUpdate = () => {
    if (!sourceVideo.value || !isLooping.value) return;
    
    const currentVideoTime = sourceVideo.value.currentTime;
    const loopEndTime = endTime.value > 0 ? endTime.value : sourceVideo.value.duration;
    
    // 如果当前时间超过结束时间，则回到开始时间
    if (currentVideoTime >= loopEndTime) {
      console.log(`到达结束时间 ${loopEndTime}s，重置到 ${startTime.value}s`);
      sourceVideo.value.currentTime = startTime.value || 0;
    }
  };

  // 组件卸载时清理事件监听
  onUnmounted(() => {
    if (sourceVideo.value) {
      sourceVideo.value.removeEventListener('timeupdate', handleTimeUpdate);
    }
  });

  return {
    isLooping,
    toggleLoopPlay,
    handleTimeUpdate
  };
}